import axios from "axios";
import NProgress from 'nprogress';
import glo_cfg from '../config'
import { Toast } from "vant";
import {getToken,setToken} from '../util/token'
import {myToast} from '../util/Alert'
import {Dialog} from 'vant'
const service = axios.create({
    baseURL:glo_cfg.api_domain,
    timeout: 30000
})

service.interceptors.request.use(config => {
    
    NProgress.start();
    if(!config.headers!.MLToken && getToken()){
        (config.headers!)['MLToken']=getToken() as string;
    }
    return config;
})

service.interceptors.response.use(data => {
    NProgress.done();
    const code=data.data.retCode;
    if(code==501){
        myToast('页面未授权或者授权已过期，正在跳转至授权页面。。。',function(){
            setToken('-1');//如果token过期，设置为-1
            location.href="/";
        })
        return Promise.reject('页面为授权');
    }else if(code == 502){
        myToast('登录已过期或未绑定账户，请重新登录',function(){
            location.href="/login";
        })
        return Promise.reject('登录已过期');
    }else if(code!=200){
        Dialog.alert({message:data.data.message});
        return Promise.reject(data.data.message);
    }else{
        return data.data;
    }
},
    err => {
        NProgress.done();
        myToast('服务器异常');
        // Dialog.alert({message:'服务器异常'});
        return Promise.reject('服务器异常');
    }
)
export default service;